<?php

namespace addons\shopro\library\teams;

use app\admin\model\shopro\teams\Config as TeamsConfigModel;
use addons\shopro\model\User as UserModel;
use addons\shopro\model\commission\Agent as AgentModel;
use addons\shopro\model\commission\Level as LevelModel;

use app\admin\model\shopro\teams\Reward  as RewardModel;
use app\admin\model\shopro\teams\Order  as OrderModel;

/**
 * 团队业务
 */
class Team
{

    public $user;     // 商城用户
    public $agent;    // 分销商用户
    public $_config;    // 分销设置
    public $parentAgentId;

    // 分销商状态 AGENT_STATUS
    const AGENT_STATUS_NORMAL = 'normal';       // 正常 
    const AGENT_STATUS_PENDING = 'pending';     // 审核中 不分佣、不打款、没有团队信息
    const AGENT_STATUS_FREEZE = 'freeze';       // 冻结 正常记录分佣、不打款，记录业绩和团队信息 冻结解除后立即打款
    const AGENT_STATUS_FORBIDDEN = 'forbidden'; // 禁用 不分佣、不记录业绩和团队信息
    const AGENT_STATUS_NULL = 'unmet';             // 未满足成为团长条件


    // 完善资料状态 INFO_STATUS
    const INFO_STATUS_REJECT = -1;  // 资料驳回
    const INFO_STATUS_NONE = 0;  // 未完善资料
    const INFO_STATUS_COMPLETED = 1;     // 已完善
    const INFO_STATUS_NULL = null;     // 无需完善资料

    // 分销商升级锁 UPGRADE_LOCK
    const UPGRADE_LOCK_OPEN = 1;  // 禁止分销商升级
    const UPGRADE_LOCK_CLOSE = 0;  // 允许分销商升级

    /**
     * 构造函数
     * 
     * @param int      $user_id     用户ID
     */
    public function __construct($user_id)
    {
        $this->user = UserModel::where('id', $user_id)->find();
        $this->agent = AgentModel::get($user_id);
        $this->_config = new Config();
    }

    // 获取团队状态
    public function getTeamStatus()
    {
        if ($this->user->is_heads == 0) {
            return self::AGENT_STATUS_NULL;
        }

        if ($this->user->heads_status == 0) {
            return self::AGENT_STATUS_FORBIDDEN;
        }
        return self::AGENT_STATUS_NORMAL;
    }

    // 获取团队可参与状态 正常和冻结都可正常浏览
    public function isTeamAvaliable()
    {
        $status = $this->getTeamStatus();
        if (in_array($status, [self::AGENT_STATUS_NORMAL])) {
            return true;
        }
        return false;
    }

    // 获取分销商等级
    public function getAgentLevel()
    {
        if (empty($this->agent)) {
            return 0;
        }
        $level = LevelModel::get($this->agent->level);
        if (!$level) {
            return 1;
        }
        return $level->level;
    }

    // 获取分销商等级信息
    public function getAgentLevelInfo()
    {
        if (empty($this->agent)) {
            return null;
        }
        $level = LevelModel::get($this->agent->level);
        if (!$level) {
            return LevelModel::get(1);;  // 找不到分销商等级 则默认为初级
        }
        return $level;
    }

    // 获取团队待入账佣金
    public function getTeamDelayMoney()
    {
        return round(RewardModel::where('heads_sid', $this->user->id)->where('status','0')->sum('commission'), 2);
    }

    // 获取团队的总订单数及总金额
    public function getTeamOrderMoney()
    {
        return OrderModel::field('sum(amount) as heads_order_money ,count(1) as heads_order_count')
            ->where('heads_sid', $this->user->id)
            ->find();
    }
    

    // 分销商升级是否锁定
    public function getAgentUpgradeLock()
    {
        if (empty($this->agent)) {
            return true;
        }
        if ($this->agent->upgrade_lock == self::UPGRADE_LOCK_OPEN) {
            return true;
        }

        return false;
    }

    // 获取团长信息 返回实时状态
    public function getTeamInfo()
    {
        $agentStatus = $this->getTeamStatus();
        // 检查用户是否达成团长条件 达成->添加团长记录
        if ($agentStatus == self::AGENT_STATUS_NULL) {
            $agentStatus = $this->becomeTeams();
        }
        $response = [
            'status' => $agentStatus,
            'data'   => null,
            'msg'    => ''
        ];

        switch ($agentStatus) {
            case self::AGENT_STATUS_NULL:
                $response['msg'] = '您暂时不能成为团长';
                break;
            case self::AGENT_STATUS_NORMAL:
                $response['data'] = $this->agent;
                $response['msg'] = '团队详情';
                break;
            case self::AGENT_STATUS_FORBIDDEN:
                $response['msg'] = '您的账户已禁用,请联系客服解决';
                break;
            case self::AGENT_STATUS_FREEZE:
                $response['data'] = $this->agent;
                $response['msg'] = '您的账户已被冻结,部分功能暂不可用';
                break;
        }
        return $response;
    }


    /**
     * 成为团长
     */
    public function becomeTeams()
    {

        $agentStatus = self::AGENT_STATUS_NULL;
        $config = TeamsConfigModel::column('value', 'name');
        // 自己是团长 不考虑其它
        if($this->user->is_heads == 1){
            return $this->user->is_heads;
        }
        $retailer_num = AgentModel::where('parent_agent_id','=',$this->user->id)->count();
        //满足成为团长条件
        if($retailer_num >= $config['retailer_num'] && $config['team_leader_type'] == '1'){
            $this->user->is_heads = 1;
            $this->user->heads_status = 1;
            $this->user->heads_sid = 0;
            $this->user->heads_time = time();
            $this->user->save();
            // 把自己的团队的人员带走
            $this->belowChangeTeams($this->user->id);

            $agentStatus = self::AGENT_STATUS_NORMAL;
        }

        return $agentStatus;
    }

    //成为团长了 就会把自己下面 间推的用户变成自己的团员
    public function  belowChangeTeams($user_id){
        (new UserModel())->save(['heads_sid'=>$this->user->id],['parent_user_id'=>$user_id]);
        $userList = (new UserModel())->field('id')->where(['parent_user_id'=>$user_id])->select();
        if($userList){
            foreach ($userList as $v){
                $this->belowChangeTeams($v['id']);
            }
        }else {
            return true;
        }
    }

    
}
